from zope.interface import implements
import os, sys

APPLICATION_INSTALL_DIR = os.environ.get('SIMPLEWATCHER_INSTALL')
if not APPLICATION_INSTALL_DIR:
    raise EnvironmentError("must set environment variable SIMPLEWATCHER_INSTALL")
sys.path.append('%s/lib' % APPLICATION_INSTALL_DIR)

from watcher.exceptions import WatcherError
from watcher.config.classbuilder import KlassBuilder
from watcher import WatcherObject
from watcher.interfaces import IReadBehavior, IOpenBehavior, ICloseBehavior


def inputQueue(name, configPath):
    """input queue will return other classes when called
    """
    return KlassBuilder(name, configPath)()(name, configPath)


class OpenBehavior(object):
    """to be subclassed such that __call__ is the right kind of open
       for the queue
    """
    implements(ICloseBehavior)

class ReadBehavior(object):
    """to be subclassed such that __call__ is the right kind of read
       for the queue
    """
    implements(IReadBehavior)

class CloseBehavior(object):
    """to be subclassed such that __call__ is the right kind of close
       for the queue
    """
    implements(ICloseBehavior)



class ReadFolder(ReadBehavior):
    """read on a directory"""
    def __init__(self, path):
        self.path = path
    
    def __call__(self):
        fileList = []
        for file in os.listdir(self.path):
            if os.path.isfile(os.path.join(self.path, file)):
                fileList.append(file)
        return fileList

class FolderQueue(WatcherObject):
    """watch on a folder"""
    def __init__(self, path, configPath=None):
        super(FolderQueue, self).__init__(path, configPath)
        if not os.path.isdir(self.config.path.xml_text_content()):
            raise WatcherError("Path %s is not a folder" % self.config.path.xml_text_content())
        self.path = self.config.path.xml_text_content()
        self.read = ReadFolder(self.path)
